
TARGET=led

BUILD_DIR=build

##### gcc
CROSS_COMPILE ?=arm-none-eabi-

CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
ld=$(CROSS_COMPILE)ld

#### src files
SRC_C=$(wildcard Src/*.c Drivers/STM32F1xx_HAL_Driver/Src/*.c)
SRC_S=startup_stm32f103xb.s

SRC_ld=STM32F103C8Tx_FLASH.ld

#### .o files
OBJ_C=$(addprefix $(BUILD_DIR)/,  $(SRC_C:.c=.o))
# OBJ_C=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_C:.c=.o)))
OBJ_s=$(BUILD_DIR)/startup_stm32f103xb.o

#### include dir
INC=-IInc \
-IDrivers/STM32F1xx_HAL_Driver/Inc \
-IDrivers/STM32F1xx_HAL_Driver/Inc/Legacy \
-IDrivers/CMSIS/Device/ST/STM32F1xx/Include \
-IDrivers/CMSIS/Include

#### CFLAGS
DEFS=-DUSE_HAL_DRIVER -DSTM32F103xB
 
CFLAGS= \
-mcpu=cortex-m3 \
-mthumb \
$(DEFS) \
-Wall \
-fdata-sections \
-ffunction-sections \
-Og \
-g \
-gdwarf-2 \
-g3 \
# -MMD -MP -MF"$(@:%.o=%.d)"
# -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) \


#### LINK 
LIBS=-lc -lm -lnosys

LDFLAGS =-mcpu=cortex-m3 \
-Wl,--gc-sections \
-specs=nano.specs -T$(SRC_ld) \
$(LIBS) \
-Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref


### .c path set
vpath %.c $(sort $(dir $(SRC_C) ))

 
#### build
.PHONY:all clean  test

all: $(BUILD_DIR) $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).bin
	@echo all

# mkdir 
$(BUILD_DIR):
	mkdir $@

# link elf
$(BUILD_DIR)/$(TARGET).elf:$(OBJ_C) $(OBJ_s)
	@echo  abc
	@$(CC) $(OBJ_C) $(OBJ_s) $(LDFLAGS) -o $@
	@$(SZ) $@

# .c -> .o
$(BUILD_DIR)/%.o : %.c
	@echo cc $< 
	@mkdir -p $(@D)
	@$(CC) -c $(CFLAGS)  $< $(INC) -o $@
	

# .s -> .o
$(OBJ_s):$(SRC_S)
	$(AS) -c $(CFLAGS) $< $(INC) -o $@

# .elf -> .bin
$(BUILD_DIR)/$(TARGET).bin:$(BUILD_DIR)/$(TARGET).elf
	$(CP) -O binary -S $< $@

clean:
	rm -rf $(BUILD_DIR)

test:
#	@echo $(SRC_C) 
	@echo $(OBJ_C)  


#-include $(wildcard $(BUILD_DIR)/*.d)